package com.lf.service.impl;

import com.lf.dao.AuthCodeDao;
import com.lf.pojo.LagouAuthCode;
import com.lf.service.AuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.ZonedDateTime;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class AuthCodeServiceImpl implements AuthCodeService {


    @Autowired
    private AuthCodeDao authCodeDao;

    @Override
    public String generateCode(String email) {
        // 生成 6位 随机验证码
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        String code = sb.toString();
        ZonedDateTime now = ZonedDateTime.now();
        // 随机验证码存储到数据库中
        LagouAuthCode authCode = new LagouAuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(now);
        authCode.setExpiretime(now.plusMinutes(10L));
        authCodeDao.save(authCode);
        return code;
    }


    // 0 正确 1 错误 2 超时
    @Override
    public Integer checkEmailAndCode(String email, String code) {
        ZonedDateTime now = ZonedDateTime.now();
        List<LagouAuthCode> codeList = authCodeDao.findAllByEmailAndExpiretimeAfterOrderByExpiretimeDesc(email, now);

        if(codeList.size() > 0) {
            String correctCode = codeList.get(0).getCode();
            if(correctCode.equals(code)) {
                return 0;
            } else {
                return 1;
            }
        } else {
            return 2;
        }
    }
}
